import MyInfo from "../entity/db1/myInfo";
import UserDao from "../dao/userDao";
import fs from 'fs';
import { File } from "../types/upload";
import platformPath from 'path';
import MyError from "../utils/myError";
const userDao = new UserDao();
export default class UserService {
    public async findMyInfoById(id: number): Promise<MyInfo> {
        return await userDao.findById(id);
    }
    public async updateMyInfoById(entity: MyInfo): Promise<number> {
        return await userDao.updateById(entity);
    }
    public async addMyInfo(entity: MyInfo): Promise<number> {
        return await userDao.insert(entity);
    }
    public async deleteUperById(id: number): Promise<MyInfo> {
        return await userDao.deleteById(id)
    }
    public async findByUsername(username: string): Promise<MyInfo> {
        return await userDao.findByUsername(username)
    }
    public saveFile(file: File): string {
        const { path: filePath, name: fileName, type: fileType, size: fileSize } = file;
        if (fileSize / 1024 / 1024 > 250) {
            throw new MyError('文件大小不能超过250M!');
        }
        // 创建输入流
        const reader = fs.createReadStream(filePath);
        // 文件的存放路径
        const savePath = platformPath.resolve(global.config.get('uploadsPath'), fileName);
        //创建输出流缓冲区
        const buffer = fs.createWriteStream(savePath, {
            flags: 'w',
            encoding: 'utf8',
        })
        // 将读取多少流写入缓冲区
        reader.pipe(buffer)
        return `http://${global.config.get('domain')}:${process.env.PORT}/uploads/${fileName}}`;
    }
}